package com.azt.back.action.enquiry;

import com.azt.api.dto.ForItemList;
import com.azt.api.dto.PurchaseModel;
import com.azt.api.enums.*;
import com.azt.api.pojo.*;
import com.azt.api.service.*;
import com.azt.api.dto.EnqEnquiryItemForm;
import com.azt.back.model.EnqQuoteItemForm;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.FreemarkerUtils;
import com.azt.utils.RequestUtils;
import com.azt.utils.SessionUtils;
import freemarker.template.TemplateModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新版询价项目
 * @author 张栋 2016年8月8日下午1:57:42
 */
@Controller
@RequestMapping("/enq")
@SessionAttributes(value = {"CPModel"})
public class EnqEnquiryAction {
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.setAutoGrowCollectionLimit(100000);
	}
	
	@Autowired
	private EnqEnquiryService enqEnquiryService;

    @Autowired
    private EnqQuoteService quoteService;

	@Autowired 
	private EnqEnquiryAnalysisService  analysisService;

	@Autowired
	private DictionaryService dictionaryService;
	

	@Autowired
	private ProCategoryService proCategoryService;

	@Autowired
	private MqProducerService mq;

	@Autowired
	private IntegralService integralService;

	@Autowired
	private MsgConfigService msgConfigService;
	@Autowired
	private CompanyService companyService;


	@Autowired
	private ConfigService configService;
	/**
	 * 采购询价项目列表
	 * 
	 * @author 张栋 2016年8月8日下午3:25:06
	 */
	@RequestMapping("/v_enquiry_list.do")
	public String v_project_list(HttpServletRequest request,ModelMap model, Integer pageNo,SessionStatus status) {
		status.setComplete();

		Map<String, String> searchMap = RequestUtils.getSearchMap(request);
		String so_enq_or = searchMap.get("so_enq_or");
		
		if(so_enq_or==null){
			searchMap.put("so_enq_or", EnqEnquiryQtypeEnum.ENQ_TYPE_CAIGOU.getIndex()+"");
		}
		
		
		Pagination pagination = enqEnquiryService.getEnqEnquiryPage(pageNo == null ? 1 : pageNo, 15, searchMap);
		model.put("pagination", pagination);

		// 项目状态
		Map<String, String> allProjectStat = EnqProjectEnum.getAllProjectStat();
		model.put("allstats", allProjectStat);

		// 询价设计状态
		Map<String, String> allEnqStat = EnqEnquiryEnum.getAllEnqStat();
		model.put("allEnqStat", allEnqStat);

		
		TemplateModel qtypes = FreemarkerUtils.getStaticModel(EnqEnquiryQtypeEnum.class);
		model.put("EnqEnquiryQtypeEnum", qtypes);


		TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqEnquiryEnum.class);
		model.put("EnqEnquiryEnum", staticModel);

		
		RequestUtils.MapToModelMap(searchMap, request);
		return "enquiry/enquiry_list";
	}


	@RequestMapping("/compnay/godname.do")
	public void godname( ModelMap model,HttpServletResponse response ){
		try {
			Integer companyid = RequestUtils.getInteger("companyid");
			Company com = companyService.getTopParentCompany(companyid);
			String name = com.getCompanyName();
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println("<div style='width:auto;height:50px;padding:5px;'>总公司:"+name+"<div>");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 报价列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @param pageNo
	 * @return
	 */
	@RequestMapping("/v_quote_list.do")
	public String v_quote_list(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer pageNo) {

		Map<String, String> searchMap = RequestUtils.getSearchMap(request);


		Pagination pagination = enqEnquiryService.getQuoteAnalysisPage(pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE, searchMap);
		model.put("pagination", pagination);

		// 项目状态
		Map<String, String> allProjectStat = EnqProjectEnum.getAllProjectStat();
		model.put("allstats", allProjectStat);

		// 报价状态
		Map<String, String> allQuoteStat = EnqQuoteEnum.getAllQuoteStat();
		model.put("allQuoteStat", allQuoteStat);

		// 询价类型
		Map<String, String> allEnquiryType = EnqEnquiryQtypeEnum.getAllStat();
		model.put("allEnquiryType", allEnquiryType);


		//TemplateModel qtypes = FreemarkerUtils.getStaticModel(EnqEnquiryQtypeEnum.class);
		//model.put("EnqEnquiryQtypeEnum", qtypes);
		//TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqEnquiryEnum.class);
		//model.put("EnqEnquiryEnum", staticModel);
		TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqQuoteEnum.class);
		model.put("EnqQuoteEnum", staticModel);


		RequestUtils.MapToModelMap(searchMap, request);
		return "enquiry/quote_list";
	}

	/**
	 * 报价分析功能
	 * @param quoteId
	 * @param excelPath
	 * @param excelName
	 * @return
	 */
	@RequestMapping("/o_anaylsis_quote.do")
	@ResponseBody
	public AjaxJson o_anaylsis_quote(Integer quoteId , String excelPath , String excelName , Integer enquiryId , Integer projectId) {

		//try {
			Map<String, Object> result = enqEnquiryService.importQuoteItem(excelPath, excelName, quoteId , enquiryId);
		//}

		if((Boolean) result.get("success")){
			AjaxJson success = AjaxJson.success();
			result.put("enquiryId" , enquiryId);
			result.put("projectId" , projectId);
			success.setAttributes(result);
			return success;
		}else {
			return AjaxJson.error(result.get("msg").toString());
		}

	}


	/**
	 * 报价审核通过 保存报价明细什么的
	 * @param request
	 * @param response
	 * @param model
	 * @param qitems
	 * @return
	 */
	@RequestMapping( value = "/o_post_quote.do" , method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson o_postQuote(HttpServletRequest request, HttpServletResponse response, ModelMap model, ForItemList qitems) {
		if(CollectionUtils.isNotEmpty(qitems.getItems()) && qitems.getQuoteId() != null){
			try {
				enqEnquiryService.passQuoteAndItems(qitems.getItems() , qitems.getQuoteId());
				return AjaxJson.success();
			} catch (Exception e) {
				e.printStackTrace();
				return AjaxJson.error(e.getMessage());
			}
		}else{
			return AjaxJson.error("参数有误");
		}
	}

	@RequestMapping( value = "/o_quote_change_state.do" , method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson o_quote_change_state(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer quoteId , Integer state , String suggest) {
		if(quoteId != null){
			try {
				enqEnquiryService.changeQuoteState(quoteId , state , suggest);
				return AjaxJson.success();
			} catch (Exception e) {
				e.printStackTrace();
				return AjaxJson.error(e.getMessage());
			}
		}else{
			return AjaxJson.error("数据有误，报价记录不存在");
		}
	}



	@RequestMapping("/v_new_enquiry_{type}.do")
	public String newEnquiryList(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer pageno , @PathVariable Integer type){
		model.put("qtype" , type);
		return "enquiry/new/enquiry_list";
	}

	@RequestMapping("/v_new_enquiry_detail.do")
	public String newEnquiryDetail(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryId){
		return "enquiry/new/enquiry_detail";
	}

	@RequestMapping("/v_new_enquiry_data.do")
	public String newEnquiryListData(HttpServletRequest request, HttpServletResponse response, ModelMap model,Integer pageNo ,
									 Integer qtype , Integer type , Integer state , Integer noMatch , Integer noOffer , Integer noOrder , Integer hasList ){
		Map<String , String > params = new HashMap<String , String>();
		params.put("qtype" ,qtype.toString());
		params.put("type" ,type.toString());
		params.put("state" ,state == null ? null : state.toString());//订单状态 是否通过
		params.put("noMatch" ,noMatch == null ? null : noMatch.toString());//未匹配
		params.put("noOffer" ,noOffer == null ? null : noOffer.toString());//未完全报价
		params.put("noOrder" ,noOrder == null ? null : noOrder.toString());//未完全下单
		params.put("hasList" ,hasList == null ? null : hasList.toString());//有清单

		Pagination pagination = enqEnquiryService.getBackEnquiryList(params, pageNo == null ? 1 : pageNo, Globals.PAGE_SIZE);

		model.put("pagination" , pagination);
		model.put("params" , params);

		Integer tipsNum = 0;
		if(qtype.compareTo(1) == 0){
			Map<String , String > searchMap = new HashMap<String , String>();
			searchMap.putAll(params);
			searchMap.put("hasList" , "1");
			tipsNum = enqEnquiryService.getBackEnquiryListNum(searchMap);
		}
		if(qtype.compareTo(2) == 0){
			if(type.compareTo(1) == 0){
				Map<String , String > searchMap = new HashMap<String , String>();
				searchMap.putAll(params);
				searchMap.put("noMatch" , "1");
				tipsNum = enqEnquiryService.getBackEnquiryListNum(searchMap);
			}
			if(type.compareTo(2) == 0){
				Map<String , String > searchMap = new HashMap<String , String>();
				searchMap.putAll(params);
				searchMap.put("noOffer" , "1");
				tipsNum = enqEnquiryService.getBackEnquiryListNum(searchMap);
			}
		}
		model.put("tipsNum" , tipsNum);

		return "enquiry/new/enquiry_data";
	}

	
	
	/**
	 * 报价更新url
	 * 
	 * @author 张栋 2016年5月11日下午3:40:55
	 */
	@RequestMapping("/o_excel_quote_update.do")
	@ResponseBody
	public AjaxJson o_excel_quote_update(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		AjaxJson j = new AjaxJson();
		String url = RequestUtils.getString(request, "url");
		Integer id = RequestUtils.getInteger(request, "id");
		EnqQuote quote = quoteService.getQuoteById(id);
		quote.setExcelpath(url);
		quoteService.saveOrUpdateQuote(quote);
		return j;
	}
	
	/**
	 * 更新url
	 *
	 * @author 张栋 2016年5月11日下午3:40:55
	 */
	@RequestMapping("/o_excel_update.do")
	@ResponseBody
	public AjaxJson o_excel_update(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		AjaxJson j = new AjaxJson();
		String url = RequestUtils.getString(request, "url");
		Integer id = RequestUtils.getInteger(request, "id");
		String name = RequestUtils.getString("name");
		EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(id);
		enquiry.setExcelpath(url);
		enquiry.setExcelName(name);
		enqEnquiryService.saveOrUpdateEnq(enquiry);
		return j;
	}



	/**
	 * 重新解析 excel
	 * 
	 * @author 张栋 2016年5月9日下午7:19:40
	 */
	@RequestMapping("/o_retry.do")
	public String o_retry(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		Integer type=1;

		try {
            Integer id = RequestUtils.getInteger(request, "id");

			//1询价,2报价
			type = RequestUtils.getInteger("type");

			String excelpath =null;
			if(type==1){
				EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(id);
				excelpath = enquiry.getExcelpath();
				model.put("enquiry", enquiry);
			}else{
				EnqQuote quote =  quoteService.getQuoteById(id);
				excelpath = quote.getExcelpath();
				model.put("quote",quote);
				Integer enquiryId = quote.getEnquiryId();
				EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(enquiryId);
				model.put("enquiry", enquiry);
			}


            // 解析
            Admin admin = ContextUtils.getAdmin();
            PurchaseModel tryPurchase = analysisService.tryPurchase(excelpath,admin.getId(), type);

            SessionUtils.broadcast("test", admin.getId(), "分析完毕");

			readyModel(model,tryPurchase);
            //还要显示匹配到的系统的名称,这个麻烦,要查类别3的,并形成map
            Map<String, Category> categorysMap = proCategoryService.getCategorysMap();
            model.put("categorysMap", categorysMap);
        } catch (Exception e) {
            e.printStackTrace();
            model.put("msg", "解析失败");
        }

		if(type==1){
			return "enquiry/enquiry_analysis_model";
		}else{
			return "enquiry/quote_analysis_model";
		}

	}

	
	/**
	 * 分组分析
	 * Created by 张栋 on 2017/3/30 15:23
	 */
	@RequestMapping("/mulity_retry.do")
	public String mulityRetry(HttpServletRequest request, ModelMap model) {
		Integer type = 1;
		boolean isMulity =false;
		try {
			Integer id = RequestUtils.getInteger(request, "id");

			type = RequestUtils.getInteger("type");

			EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(id);
			// 解析
			Admin admin = ContextUtils.getAdmin();
			model.put("enquiry", enquiry);
			List<PurchaseModel> excelMulityWraps = analysisService.tryPurchaseMulity(enquiry.getExcelpath(), admin.getId(), type);
			if(excelMulityWraps.size() >1 ){
				//CPModel 保存到session
				model.put("CPModel",excelMulityWraps);
				model.put("wrapsize",excelMulityWraps.size());
				isMulity=true;
			}else if(excelMulityWraps.size()==1){
				readyModel(model, excelMulityWraps.get(0));
			}

			SessionUtils.broadcast("test", admin.getId(), "分析完毕");
		} catch (Exception e) {
			e.printStackTrace();
		}

		if(isMulity){
			return "enquiry/enquiry_analysis_mulity_model";
		}else{
			return "enquiry/enquiry_analysis_model";
		}


	}

	/**
	 * 多tab情况下的每一个tab请求
	 * Created by 张栋 on 2017/3/30 15:24
	 */
	@RequestMapping("/mulity_one.do")
	public String mulityOne( ModelMap model,Integer index,Integer enqid){
		List<PurchaseModel> excelMulityWraps  = (List<PurchaseModel>) model.get("CPModel");

		model.put("mulityAnalysis",true);
		PurchaseModel purchaseModel  =excelMulityWraps.get(index);
		readyModel(model, purchaseModel);

		EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(enqid);
		// 解析
		model.put("enquiry", enquiry);

		return "enquiry/enquiry_analysis_model";
	}






	/**
	 * 装model
	 * Created by 张栋 on 2017/3/30 15:26
	 */
	private void readyModel(ModelMap model, PurchaseModel tryPurchase) {
		List<String> titles = tryPurchase.getTitles();
		model.put("titles", titles);
		List<Integer> titleindex = tryPurchase.getTitleindex();
		model.put("titleindex", titleindex);
		//是否完美匹配
		model.put("titlePerfect", tryPurchase.isTitlePerfect());
		//最长列
		model.put("maxlength", tryPurchase.getMaxlength());

		model.put("contents", tryPurchase.getContents());

		model.put("cellStats", tryPurchase.getCellStats());

		//没有被匹配的行
		model.put("nocontents", tryPurchase.getNocontents());

		model.put("contentPerfect", tryPurchase.isContentPerfect());

		model.put("shebeiindex", tryPurchase.getShebeiindex());

		model.put("md5secret", tryPurchase.getShebeiscret());

		//还要显示匹配到的系统的名称,这个麻烦,要查类别3的,并形成map
		Map<String, Category> categorysMap = proCategoryService.getCategorysMap();
		model.put("categorysMap", categorysMap);
	}




	//上班开始时间与截止时间
	@Value("${sms.delay.start}")
	private String start;
	@Value("${sms.delay.end}")
	private String end;
	/**
	 * 修改审核状态提示页
	 * 
	 * @author 张栋 2016年5月17日下午2:45:31
	 */
	@RequestMapping("/v_prostate_change.do")
	public String v_prostate_change(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryid, Integer prostate) {
		
		EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(enquiryid);
		model.put("enquiry", enquiry);
		model.put("enquiryid", enquiryid);
		model.put("prostate", prostate);
		
		/*
		User user =uesrService.getUserById(enquiry.getEnqProject().getUserId());
		model.put("phone", user.getMobile());
		model.put("email", user.getEmail());
		*/

		String contacts = enquiry.getContacts();
		String phone = enquiry.getPhone();
		model.put("contacts",contacts);
		model.put("phone",phone);

		Map<String, String> allStates = EnquiryProstateEnum.getAllStates();
		model.put("allStates", allStates);

		Integer numsize = null;
		if((enquiry.getHadsendsms()==null || enquiry.getHadsendsms()==0) && prostate!=2){
			//查看条数,预警,不发送
			if(enquiry.getQtype()==1){
				numsize =enqEnquiryService.getNeedPubSMS(enquiryid,null,false);
			}else{
				if(enquiry.getPubtype()==1){
					numsize =enqEnquiryService.getNeedPubSMS(enquiryid,null,false);
				}else{
					numsize =enqEnquiryService.getNeedSMS(enquiryid,null,false);
				}
			}

			model.put("numsize",numsize);
		}

		//上班时间
		String worktime = start.substring(0,2)+":"+start.substring(2)+"-"+end.substring(0,2)+":"+end.substring(2);
		model.put("worktime",worktime);

		return "enquiry/change_state_model";
	}
	
	
	
    /**
     * 保存item 详细列表
     *
     * @author 张栋 2016年5月17日下午2:44:23
     */
    @RequestMapping("/o_saveitem.do")
    @ResponseBody
    public AjaxJson o_saveitem(HttpServletRequest request, @RequestBody EnqEnquiryItemForm item) {

		AjaxJson j = new AjaxJson();
		String[] typenames =item.getTypenames();
		String[] oldtitles =item.getOldtitles();
		

		// 保存或者更新item ,先删除后添加
		enqEnquiryService.saveOrUpdateEnquiryItem(item.getEnquiryid(), item.getItem());
		
		//保存数据到仓库
		analysisService.saveOrUpdateRepository(item.getItem());
		//保存标题
		analysisService.saveOrUpdateRepositoryTitles(typenames, oldtitles, 1);

        return j;
    }



    /**
     * 保存报价分析
     * 使用与询价相同的item方便数据的处理
     * 内部再转换成报价使用的item
     * Created by 张栋 on 2016/11/1 9:41
     */
    @RequestMapping("/o_save_quote_item.do")
    @ResponseBody
    public AjaxJson o_save_quote_item(HttpServletRequest request,@RequestBody EnqQuoteItemForm item){

        AjaxJson j = new AjaxJson();

        String[] typenames = item.getTypenames();
        String[] oldtitles = item.getOldtitles();

        //仅做保存,不保存信息到仓库
        Boolean onlysave = RequestUtils.getBoolean("onlysave", false);


        // 保存或者更新item ,先删除后添加
        quoteService.saveOrUpdateQuoteItem(item.getQuoteid(), item.getItem());

        if(!onlysave){
            //保存数据到仓库
			quoteService.saveOrUpdateRepository(item.getItem());
            //保存标题
            analysisService.saveOrUpdateRepositoryTitles(typenames, oldtitles,2);
        }
        return j;
    }

	  
		/**
		 * item列表的分页
		 * 详情页可以编辑,则为方便处理,去掉分页 ,暂时直接将每页数量设置为1W,
		 * @author 张栋  2016年7月28日下午1:49:28
		 */
		@RequestMapping("/v_enquiry_item.do")
		public String itemlist(HttpServletRequest request, Integer pageNo, HttpServletResponse response, ModelMap model) {

			Map<String, String> searchMap = RequestUtils.getSearchMap(request);
			String so_enquiryid = searchMap.get("so_enquiryid");
			Integer  enquiryid = Integer.parseInt(so_enquiryid);
			EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(enquiryid);
			model.put("enquiry", enquiry);
			
			List<EnqEnquiryItem> enquiryItems  =  enqEnquiryService.getEnquiryItem(enquiryid);
			model.put("enquiryItems", enquiryItems);
			
			Map<String, String> provinces = dictionaryService.getChinaProvinces();
			if (!provinces.isEmpty()) {
				model.put("provinces", provinces);
			}
			
			TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqEnquiryEnum.class);
			model.put("EnqEnquiryEnum", staticModel);
			
			TemplateModel enqEnquiryTaxEnum = FreemarkerUtils.getStaticModel(EnqEnquiryTaxEnum.class);
			model.put("EnqEnquiryTaxEnum", enqEnquiryTaxEnum);
			
			// RequestUtils.MapToModelMap(searchMap, request);
			return "enquiry/enquiry_item_list";
		}


	/**
	 * 报价明细列表
	 * @param request
	 * @param model
	 * @return
	 */
		@RequestMapping("/v_quote_item.do")
		public String quoteItemlist(HttpServletRequest request, ModelMap model) {

			Map<String, String> searchMap = RequestUtils.getSearchMap(request);
			//String so_enquiryid = searchMap.get("so_enquiryid");
			String so_quoteid = searchMap.get("so_quoteid");
			//Integer  enquiryid = Integer.parseInt(so_enquiryid);
			Integer  quoteid = Integer.parseInt(so_quoteid);


			EnqQuote quote = enqEnquiryService.getEnqQuoteById(quoteid);
			model.put("quote", quote);
			model.put("solvepath", quote.getFile1());
			model.put("tppath", quote.getFile2());
			EnqEnquiry enquiry = enqEnquiryService.getEnquiryById(quote.getEnquiryId());
			model.put("enquiry", enquiry);

			List<EnqQuoteItem> quoteItems = enqEnquiryService.getItemByQuote(quoteid);
			model.put("quoteItems", quoteItems);

			//List<EnqEnquiryItem>  enquiryItems  =  enqEnquiryService.getEnquiryItem(enquiryid);
			//model.put("enquiryItems", enquiryItems);

			//Map<String, String> provinces = dictionaryService.getChinaProvinces();
			//if (!provinces.isEmpty()) {
			//	model.put("provinces", provinces);
			//}

			TemplateModel staticModel = FreemarkerUtils.getStaticModel(EnqQuoteEnum.class);
			model.put("EnqQuoteEnum", staticModel);


			// 报价状态
			Map<String, String> allQuoteStat = EnqQuoteEnum.getAllQuoteStat();
			model.put("allQuoteStat", allQuoteStat);
            //
			//TemplateModel enqEnquiryTaxEnum = FreemarkerUtils.getStaticModel(EnqEnquiryTaxEnum.class);
			//model.put("EnqEnquiryTaxEnum", enqEnquiryTaxEnum);

			return "enquiry/quote_item_list";
		}

		
		/**
		 * 修改审核状态
		 * @author 张栋 2016年5月16日下午3:15:09
		 */
		@RequestMapping("/o_prostate_changed.do")
		@ResponseBody
		public AjaxJson o_prostate_changed(HttpServletRequest request, HttpServletResponse response, ModelMap model, Integer enquiryid, Integer prostate) {
			//验证是否可以退回(有通过的报价,就不能再退回)
			if(EnquiryProstateEnum.PROSTATE_BACK.getIndex() == prostate) {//退回前验证
				//验证是否可以退回(有通过的报价,就不能再退回)
				Integer count = enqEnquiryService.getQuoteCountEnqStat(enquiryid, 1);
				if (count != 0) {
					return AjaxJson.error("该询价有通过审核的报价,不能退回");
				}
			}


			EnqEnquiry enquiry = enqEnquiryService.changeEnquiryState(enquiryid, prostate);
			Integer userId = enquiry.getUserId();
			Integer smscheck = RequestUtils.getInteger(request, "smscheck", 0);//推送采购商
			Integer typesmscheck = RequestUtils.getInteger(request, "typesmscheck", 0);//推送供应商

			if (mq!=null && enquiry.getState().equals(prostate)){
				Map<String, String> params =new HashMap<>();
				params.put("enquirytitle", enquiry.getEnquiryName());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				params.put("pubtime", sdf.format(enquiry.getPubdate()));

				String ipurl = "http://"+configService.getConfigValueByCode("WEB_SITE");
				if(EnquiryProstateEnum.PROSTATE_BACK.getIndex() == prostate){//退回
					//退回原因
					String  backreason= RequestUtils.getString(request, "backreason");
					if(backreason==null)backreason="";
					enquiry.setBackreason(backreason);
					//保存退回原因
					enqEnquiryService.saveOrUpdateEnq(enquiry);

                    if(smscheck==1){
					    //发送退回原因

					    String  url =ipurl+"/enquiry/purchase/detail/"+enquiry.getId();
					    params.put("backreason",backreason);
					    //张栋: 819
					    msgConfigService.sendMessage("ENQ_STAT_BACK",params,url,enqEnquiryService.needely(),userId);
                    }
				}else{//通过审核


					//处理下可能的老数据
					if(enquiry.getFirstPass()==null){
						enquiry.setFirstPass(0);
						enqEnquiryService.saveOrUpdateEnq(enquiry);
					}

					if(enquiry.getFirstPass()==1){
						enquiry.setFirstPass(0);
						try {
							addRecord(enquiry);
						} catch (Exception e) {
							e.printStackTrace();
							enquiry.setFirstPass(1);
						}
						enqEnquiryService.saveOrUpdateEnq(enquiry);
					}

					if(smscheck==1){//通知采购方
						String  url =ipurl+"/enquiry/purchase/detail/"+enquiry.getId();
						msgConfigService.sendMessage("ENQ_STAT_POSTED",params,url,enqEnquiryService.needely(),userId);
					}


					//typesmscheck,给相关供应商发送短信提醒
					if(typesmscheck==1 && (enquiry.getHadsendsms()==null || enquiry.getHadsendsms()==0)){
						String url =ipurl +"/enquiry/pushEnquiry_"+enquiry.getQtype()+"/list";
						if(enquiry.getQtype()==2){//采购询价分为公开与不公开
						/*发布的类型(1.公开发布 ;2.不公开发布)*/
							if(enquiry.getPubtype()==1){
								//发送短信
								enqEnquiryService.getNeedPubSMS(enquiryid,url,true);
							}else{
								//获取邀请的
								enqEnquiryService.getNeedSMS(enquiryid,url,true);
							}
						}else{
							enqEnquiryService.getNeedPubSMS(enquiryid,url,true);
						}

						//更新数据库
						enquiry.setHadsendsms(1);
						enqEnquiryService.saveOrUpdateEnq(enquiry);
					}
				}
			}
			return AjaxJson.success("操作成功");
		}

	private void addRecord(EnqEnquiry enquiry){
		Admin admin = ContextUtils.getAdmin();
		Integer adminid = null;
		if(admin!=null){
            adminid = admin.getId();
        }
		//购送积分
		Integer userid = enquiry.getUserId();
		String code = enquiry.getQtype()==1?"publish_budget":"publish_lists";
		String msg =enquiry.getQtype()==1?"预算询价":"采购询价";
		integralService.addUserRecord(userid, code,null,null, adminid);
	}




}
